package com.work.controller;

import com.work.pojo.User;
import com.work.service.UserService;
import com.work.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;

public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute( "user" );
        System.out.println( "自动登录启动" );
        Cookie[] cookies = request.getCookies();
        if (user == null && cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("user".equals( cookie.getName() )) {
                    String decode = URLDecoder.decode( cookie.getValue(), "utf-8" );
                    String[] split = decode.split( "#" );
                    User login = userService.login( split[0], split[1] );
                    request.getSession().setAttribute( "user", login );
                    System.out.println( login );
                    return true;
                }
            }
            System.out.println( "自动登录" );
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle( request, response, handler, modelAndView );
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion( request, response, handler, ex );
    }

}
